package com.yr.ryjk.coin.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.yr.ryjk.coin.dao.CoinRecordMapper;
import com.yr.ryjk.coin.dao.DayCoinMapper;
import com.yr.ryjk.coin.dao.ShareAppRecordMapper;
import com.yr.ryjk.coin.entity.CoinRecord;
import com.yr.ryjk.coin.entity.DayCoin;
import com.yr.ryjk.coin.entity.ShareAppRecord;
import com.yr.ryjk.coin.vo.CoinVO;
import com.yr.ryjk.common.Constant;
import com.yr.ryjk.common.ErrorType;
import com.yr.ryjk.common.Pagination;
import com.yr.ryjk.doctor.dao.DoctorMapper;
import com.yr.ryjk.doctor.entity.Doctor;
import com.yr.ryjk.param.dao.ParamMapper;
import com.yr.ryjk.param.entity.Key;
import com.yr.ryjk.pay.dao.CashOutMapper;
import com.yr.ryjk.redis.JedisUtil;
import com.yr.ryjk.user.dao.UserMapper;
import com.yr.ryjk.user.entity.User;
import com.yr.ryjk.util.DateUtil;
import com.yr.ryjk.util.IDGenerator;
import com.yr.ryjk.util.JSONUtil;

@Service
public class CoinService implements ICoinService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private DoctorMapper doctorMapper;
	@Autowired
	private ParamMapper paramMapper;
	@Autowired
	private DayCoinMapper dayCoinMapper;
	@Autowired
	private CoinRecordMapper coinRecordMapper;
	@Autowired
	private CashOutMapper cashOutMapper;
	@Autowired
	private ShareAppRecordMapper  shareAppRecordMapper;
	
	@Override
	public Map<String, Object> updateTakeTodayCoin(String token) {
		String phone=JedisUtil.getPhoneByToken(token);
		User user=userMapper.selectUserByPhone(phone);
		//1.验证是否已经领取过
		Date now=new Date();
		DayCoin dc=dayCoinMapper.selectByPhoneAndDate(phone,DateUtil.getYMDOfDate(now));
		if(dc!=null){
			return JSONUtil.getJSON(ErrorType.COIN_HAS_TOKEN_ERROR);
		}
		//2.每日领取的数量
		int coin=Integer.parseInt(paramMapper.selectCountByKey(Key.day_take_coin.getKey())); //每日领取的数量
		//3.插入新领取记录
		dc=new DayCoin();
		dc.setDayCoinId(IDGenerator.gen32UUID());
		dc.setUserPhone(phone);
		dc.setDay(now);
		dc.setReceiveTime(now);
		dayCoinMapper.insert(dc);
		//4.coin收支记录
		CoinRecord cr=new CoinRecord();
		cr.setCoinRecordId(IDGenerator.gen32UUID());
		cr.setOperateTime(now);
		cr.setUserId(user.getId());
		cr.setCount(coin);
		cr.setType(5);
		cr.setContent("每日领取活动中领取"+coin+"个健康币");
		coinRecordMapper.insert(cr);
		//5.更新用户健康币
		int newCoinCount=user.getCoin()+coin;
		userMapper.updateCoinById(newCoinCount, DigestUtils.md5DigestAsHex(
				(newCoinCount+Constant.COIN_MD5_SECRET_KEY).getBytes()), user.getId());
		return JSONUtil.getJSON(ErrorType.SUCCESS,coin);
	}

	@Override
	public Map<String, Object> getCoinRecord(int pageNo, int pageSize, String token) {
		String phone=JedisUtil.getPhoneByToken(token);
		Doctor doctor=doctorMapper.selectByPhone(phone);
		User user=null;
		CoinVO coinVO=new CoinVO();
		String id=null;
		if(doctor!=null){
			id=doctor.getId();
			coinVO.setAvailCoin(doctor.getCoin());
			coinVO.setTotalCoin(doctor.getTotalGainCoin());
			coinVO.setFrozenCoin(cashOutMapper.selectTotalFrozenCoin(doctor.getId()));
		}else {
			user=userMapper.selectUserByPhone(phone);
			if(user==null){
				return JSONUtil.getJSON(ErrorType.TOKEN_ERROR);
			}
			id=user.getId();
			coinVO.setAvailCoin(user.getCoin());
			coinVO.setFrozenCoin(0);
			coinVO.setTotalCoin(0);
		}
		List<CoinRecord> list=coinRecordMapper.selectOfPage((pageNo-1)*pageSize,pageSize,id);
		int totalCount=coinRecordMapper.selectCount(id);
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("list", list);
		map.put("pagination", new Pagination(pageSize, pageNo, totalCount));
		map.put("coin", coinVO);
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> insertShareAppGetCoin(String token) {
		int coin= Integer.parseInt(paramMapper.selectCountByKey(Key.share_app_get_coin.getKey())); //每次分享获得 健康币
		int everyDayGetCoinTimes = Integer.parseInt(paramMapper.selectCountByKey(Key.share_app_get_coin_times.getKey())); //每个帐号可获取的次数
		//1,分享领取健康币

		User user =  userMapper.selectUserByPhone(JedisUtil.getPhoneByToken(token));
		int todayShareTimes = shareAppRecordMapper.selectCountByPrimaryKey(user.getId());//当前帐号今日已经领取的次数
		
		int oldCoin = user.getCoin();//原来的健康币
		int newCoin = coin + oldCoin;
		
		//2,用户表更新领取的健康币
		if(todayShareTimes < everyDayGetCoinTimes){
			ShareAppRecord record = new ShareAppRecord();
			record.setShareAppRecordId(IDGenerator.gen32UUID());
			record.setAmount(coin);
			record.setUserId(user.getId());
			record.setGetTime(new Date());
			
			shareAppRecordMapper.insert(record);
			userMapper.updateCoinById(newCoin, user.getCoinMd5(), user.getId());
			
			return JSONUtil.getJSON(ErrorType.SUCCESS,coin);
		}else{
			return JSONUtil.getJSON(ErrorType.SHARE_APP_RECORD_TIMES);	
		}
	}
}